const axios = require('axios');
const fs = require('fs');
const path = require('path');
const puppeteer = require('puppeteer');
const config = require('../config/config');

class VideoDownloader {
    constructor() {
        if (!fs.existsSync(config.TEMP_DIR)) {
            fs.mkdirSync(config.TEMP_DIR, { recursive: true });
        }
    }

    async downloadVideo(videoId, retryCount = 3) {
        console.log(`开始下载视频，ID: ${videoId}`);
        try {
            const browser = await puppeteer.launch({
                headless: true,
                args: ['--no-sandbox', '--disable-setuid-sandbox']
            });
            console.log('浏览器启动成功');
            
            const page = await browser.newPage();
            await page.setUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36');
            console.log('浏览器页面初始化完成');
            
            let videoUrl = null;
            let retries = 0;
            
            while (!videoUrl && retries < retryCount) {
                try {
                    console.log(`正在尝试第 ${retries + 1} 次获取视频...`);
                    await page.setRequestInterception(true);
                    
                    page.on('request', request => {
                        if (request.resourceType() === 'media') {
                            videoUrl = request.url();
                            console.log('找到视频URL:', videoUrl);
                        }
                        request.continue();
                    });

                    console.log(`正在访问视频页面: https://www.douyin.com/video/${videoId}`);
                    await page.goto(`https://www.douyin.com/video/${videoId}`, {
                        waitUntil: 'networkidle0',
                        timeout: 30000
                    });
                    console.log('页面加载完成');

                    console.log('等待视频元素加载...');
                    await page.waitForSelector('video', { timeout: 10000 });
                    console.log('视频元素加载成功');
                    
                    if (!videoUrl) {
                        throw new Error('未找到视频URL');
                    }

                    console.log('开始下载视频文件...');
                    const response = await axios({
                        method: 'GET',
                        url: videoUrl,
                        responseType: 'stream',
                        timeout: 30000,
                        headers: {
                            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36',
                            'Referer': 'https://www.douyin.com/'
                        }
                    });

                    const videoPath = path.join(config.TEMP_DIR, `${videoId}.mp4`);
                    console.log('视频将保存至:', videoPath);
                    const writer = fs.createWriteStream(videoPath);

                    return new Promise((resolve, reject) => {
                        response.data.pipe(writer);
                        writer.on('finish', () => {
                            console.log('视频下载完成');
                            resolve(videoPath);
                        });
                        writer.on('error', (err) => {
                            console.error('视频写入失败:', err.message);
                            reject(err);
                        });
                    });

                } catch (error) {
                    retries++;
                    console.log(`下载重试 ${retries}/${retryCount}:`, error.message);
                    if (retries === retryCount) {
                        throw error;
                    }
                    console.log('等待2秒后重试...');
                    await new Promise(resolve => setTimeout(resolve, 2000));
                }
            }

            console.log('关闭浏览器');
            await browser.close();
        } catch (error) {
            console.error('视频下载失败:', error.message);
            return null;
        }
    }
}

module.exports = VideoDownloader;